package com.example.xinli.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xinli.R;
import com.example.xinli.model.Comment;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> {
    private List<Comment> commentList;
    private String currentUser;

    public CommentAdapter(List<Comment> commentList, String currentUser) {
        this.commentList = commentList;
        this.currentUser = currentUser;
    }

    @NonNull
    @Override
    public CommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_comment, parent, false);
        return new CommentViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CommentViewHolder holder, int position) {
        Comment comment = commentList.get(position);
        holder.bind(comment);
    }

    @Override
    public int getItemCount() {
        return commentList.size();
    }

    class CommentViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAvatar;
        TextView tvNickname, tvTime, tvContent;

        public CommentViewHolder(@NonNull View itemView) {
            super(itemView);
            ivAvatar = itemView.findViewById(R.id.iv_comment_avatar);
            tvNickname = itemView.findViewById(R.id.tv_comment_nickname);
            tvTime = itemView.findViewById(R.id.tv_comment_time);
            tvContent = itemView.findViewById(R.id.tv_comment_content);
        }

        public void bind(Comment comment) {
            tvNickname.setText(comment.getNickname());
            tvContent.setText(comment.getContent());

            // 格式化时间
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
            tvTime.setText(sdf.format(new Date(comment.getTimestamp())));

            // 加载用户头像
            loadUserAvatar(comment.getUsername());
        }

        private void loadUserAvatar(String username) {
            // 这里可以加载用户头像，暂时使用默认头像
            ivAvatar.setImageResource(R.drawable.ic_person);
        }
    }
}
